package cn.com.easttech.gofishing;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SubMenu;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import cn.com.easttech.gofishing.model.Company;
import cn.com.easttech.gofishing.model.ProductCatalog;
import cn.com.easttech.gofishing.model.ProductInfo;
import cn.com.easttech.gofishing.util.DBHelper;

public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private RecyclerView mRecyclerView;
    //    private List<String> mDatas;
    private HomeAdapter mAdapter;

    private DBHelper dbHelper = null;
    private List<Company> allCompanyList = new ArrayList<>();
    private List<ProductCatalog> allProductCatalogList = new ArrayList<>();
    private List<ProductInfo> allProductInfoList = new ArrayList<>();
    private List<ProductInfo> productInfoList = new ArrayList<>();

    protected void initData() {
//        mDatas = new ArrayList<String>();
//        for (int i = 'A'; i < 'z'; i++) {
//            mDatas.add("" + (char) i);
//        }

        String path = new File(getApplicationContext().getFilesDir().getAbsolutePath(), "product.json").getAbsolutePath();
        Log.d(TAG, path);

        SQLiteDatabase db = dbHelper.getWritableDatabase();


        Cursor cursor = db.query("COMPANY", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                Company company = new Company();
                company.setUuid(cursor.getString(cursor.getColumnIndex("UUID")));
                company.setName(cursor.getString(cursor.getColumnIndex("NAME")));

                allCompanyList.add(company);
            } while (cursor.moveToNext());
        }

        cursor = db.query("PRODUCT_CATALOG", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                ProductCatalog productCatalog = new ProductCatalog();
                productCatalog.setUuid(cursor.getString(cursor.getColumnIndex("UUID")));
                productCatalog.setName(cursor.getString(cursor.getColumnIndex("NAME")));
                productCatalog.setSuperCatalogId(cursor.getString(cursor.getColumnIndex("SUPER_CATALOG_ID")));
                productCatalog.setCompanyUuid(cursor.getString(cursor.getColumnIndex("COMPANY_UUID")));
                productCatalog.setSortNo(cursor.getInt(cursor.getColumnIndex("SORT_NO")));

                allProductCatalogList.add(productCatalog);
            } while (cursor.moveToNext());
        }

        cursor = db.query("PRODUCT_INFO", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                ProductInfo productInfo = new ProductInfo();
                productInfo.setUuid(cursor.getString(cursor.getColumnIndex("UUID")));
                productInfo.setName(cursor.getString(cursor.getColumnIndex("NAME")));
                productInfo.setPicture(cursor.getString(cursor.getColumnIndex("PICTURE")));
                productInfo.setTextDesc(cursor.getString(cursor.getColumnIndex("TEXT_DESC")));
                productInfo.setVideoDesc(cursor.getString(cursor.getColumnIndex("VIDEO_DESC")));
                productInfo.setPictureDesc(cursor.getString(cursor.getColumnIndex("PICTURE_DESC")));
                productInfo.setCatalogUuid(cursor.getString(cursor.getColumnIndex("CATALOG_UUID")));
                productInfo.setCompanyUuid(cursor.getString(cursor.getColumnIndex("COMPANY_UUID")));
                productInfo.setSortNo(cursor.getInt(cursor.getColumnIndex("SORT_NO")));
                productInfo.setNewProduct(cursor.getString(cursor.getColumnIndex("NEW_PRODUCT")));

                allProductInfoList.add(productInfo);
            } while (cursor.moveToNext());
        }

        for (ProductCatalog pc1 : allProductCatalogList) {
            for (Company company : allCompanyList) {
                if (pc1.getCompanyUuid().equals(company.getUuid()) && (pc1.getSubProductCatalog() == null || pc1.getSuperCatalogId().isEmpty())) {
                    company.getProductCatalogList().add(pc1);
                }
            }

            for (ProductCatalog pc2 : allProductCatalogList) {
                if (pc1.getCompanyUuid().equals(pc2.getCompanyUuid()) && pc1.getUuid().equals(pc2.getSuperCatalogId())) {
                    pc1.getSubProductCatalog().add(pc2);
                    pc2.setSuperProductCatalog(pc1);
                }
            }

            for (ProductInfo productInfo : allProductInfoList) {
                if (productInfo.getCompanyUuid().equals(pc1.getCompanyUuid()) && productInfo.getCatalogUuid().equals(pc1.getUuid())) {
                    pc1.getProductInfoList().add(productInfo);
                }
            }
        }

        if (allProductCatalogList.size() > 0) {
            ProductCatalog productCatalog = allProductCatalogList.get(0).getSubProductCatalog().get(0);
            selectProductCatalog(productCatalog);
        }

    }

    private void setCompany(Company company) {

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

        View headerLayout = navigationView.getHeaderView(0);

        TextView companyNameView = (TextView) headerLayout.findViewById(R.id.nav_company_name);
        companyNameView.setText(company.getName());

    }

    private void setTitle(ProductCatalog productCatalog) {
        try {
            setTitle(productCatalog.getSuperProductCatalog().getName() + " > " + productCatalog.getName());
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private void selectProductCatalog(ProductCatalog productCatalog) {
        productInfoList.clear();
        productInfoList.addAll(productCatalog.getProductInfoList());
    }

    private void initNavigationMenu() {
        Log.i(TAG, "initNavigationMenu");
        try {
            NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

            if (allCompanyList.size() > 0) {
                setCompany(allCompanyList.get(0));
            }

            int index = 0;
            for (int i = 0; i < allProductCatalogList.size(); i++) {
                ProductCatalog productCatalog = allProductCatalogList.get(i);

                SubMenu subMenu = navigationView.getMenu().addSubMenu(i, index, index, productCatalog.getName());

                index++;

                for (int j = 0; j < productCatalog.getSubProductCatalog().size(); j++) {
                    ProductCatalog subProductCatalog = productCatalog.getSubProductCatalog().get(j);

                    subMenu.add(i, index, index, subProductCatalog.getName());

                    index++;
                }

            }

            if (allProductCatalogList.size() > 0) {
                setTitle(allProductCatalogList.get(0).getSubProductCatalog().get(0));
            }

        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.TAG = this.getClass().getSimpleName();

        Log.d(TAG, "onCreate");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dbHelper = new DBHelper(this, "GoFishing.db", null, 6);
        dbHelper.getWritableDatabase();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        initData();

        initNavigationMenu();

        mRecyclerView = (RecyclerView) findViewById(R.id.product_list_recycler);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mAdapter = new HomeAdapter());
        //mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this));
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        mAdapter.setOnItemClickLitener(new OnItemClickLitener() {

            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(MainActivity.this, position + " click", Toast.LENGTH_SHORT).show();

                List<ProductInfo> newProductList = new ArrayList<>();
                for (ProductInfo productInfo : allProductInfoList) {
                    if ("1".equals(productInfo.getNewProduct())) {
                        newProductList.add(productInfo);
                    }
                }
                ProductInfoActivity.startAction(MainActivity.this, productInfoList.get(position), newProductList);
            }

            @Override
            public void onItemLongClick(View view, int position) {
//                Toast.makeText(MainActivity.this, position + " long click", Toast.LENGTH_SHORT).show();
            }
        });

//        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        Log.d(TAG, "onBackPressed");
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.d(TAG, "onCreateOptionsMenu");
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.main, menu);

        if (allCompanyList.size() >= 0) {
            for (int i = 0; i < allCompanyList.size(); i++) {
                Log.d(TAG, "onCreateOptionsMenu i:" + i);
                menu.add(1, i, i, allCompanyList.get(i).getName());
            }
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.d(TAG, "onOptionsItemSelected");
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        int order = item.getOrder();

        Log.d(TAG, "id:" + id + ", order:" + order);

        Company company = allCompanyList.get(order);
        setCompany(company);

        ProductCatalog productCatalog = company.getProductCatalogList().get(0).getSubProductCatalog().get(0);
        selectProductCatalog(productCatalog);
        mAdapter.notifyDataSetChanged();

        setTitle(productCatalog);

        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        Log.d(TAG, "onNavigationItemSelected");
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        int order = item.getOrder();

        Log.d(TAG, "id:" + id + ", order:" + order);

        ProductCatalog productCatalog = allProductCatalogList.get(order);
        selectProductCatalog(productCatalog);
        mAdapter.notifyDataSetChanged();

        setTitle(productCatalog);

//        if (id == R.id.nav_camera) {
//            // Handle the camera action
//        } else if (id == R.id.nav_gallery) {
//
//        } else if (id == R.id.nav_slideshow) {
//
//        } else if (id == R.id.nav_manage) {
//
//        } else if (id == R.id.nav_share) {
//
//        } else if (id == R.id.nav_send) {
//
//        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //点击的为返回键
        if (keyCode == event.KEYCODE_BACK) {
            exit();// 退出方法
        }
        return true;
    }

    class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {
        private OnItemClickLitener mOnItemClickLitener;

        public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
            this.mOnItemClickLitener = mOnItemClickLitener;
        }

        private Drawable loadImageFromWebOperations(String url) {
            try {
                InputStream is = (InputStream) new URL(url).getContent();
                Drawable d = Drawable.createFromStream(is, "src name");
                return d;
            } catch (Exception e) {
                System.out.println("Exc=" + e);
                return null;
            }
        }

        public Bitmap getBitmapFromURL(String src) {
            try {
                Log.d("src", src);
                URL url = new URL(src);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(input);
                Log.e("Bitmap", "returned");
                return myBitmap;
            } catch (IOException e) {
                Log.e("getBitmapFromURL", e.getMessage());
                return null;
            }
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
                    MainActivity.this).inflate(R.layout.product_list_main, parent,
                    false));
            return holder;
        }

        @Override
        public void onBindViewHolder(final MyViewHolder holder, int position) {
            final ProductInfo productInfo = productInfoList.get(position);

            Log.d("onBindViewHolder", productInfo.getPicture());
//            ImageLoader.showImage(productInfo.getPicture(), holder.imageView);

            holder.imageView.setImageDrawable(loadImageFromWebOperations(productInfo.getPicture()));

//            new Thread() {
//                public void run() {
//                    Bitmap bimage = getBitmapFromURL(productInfo.getPicture());
//                    holder.imageView.setImageBitmap(bimage);
//                }
//            }.start();

            holder.textView.setText(productInfo.getName());

            // 如果设置了回调，则设置点击事件
            if (mOnItemClickLitener != null) {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getLayoutPosition();
                        mOnItemClickLitener.onItemClick(holder.itemView, pos);
                    }
                });

                holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int pos = holder.getLayoutPosition();
                        mOnItemClickLitener.onItemLongClick(holder.itemView, pos);
                        return false;
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return productInfoList.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {

            ImageView imageView;
            TextView textView;

            public MyViewHolder(View view) {
                super(view);
                imageView = view.findViewById(R.id.product_image);
                textView = view.findViewById(R.id.product_name);
            }
        }
    }

}
